package reflect;

import domin.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo3 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Student> studentClass = Student.class;
        Field ageFiled = studentClass.getDeclaredField("age");
        Field nameFiled = studentClass.getDeclaredField("name");

        nameFiled.setAccessible(true);
        ageFiled.setAccessible(true);

        Constructor<Student> constructor = studentClass.getConstructor();
        Student stu1 = constructor.newInstance();
        Student stu2 = constructor.newInstance();

        //set方法
        ageFiled.set(stu1,23);
        nameFiled.set(stu1,"John");
        ageFiled.set(stu2,63);
        nameFiled.set(stu2,"xxx");
        System.out.println(stu1);
        System.out.println(stu2);

        //get方法
        System.out.println(ageFiled.get(stu1));
        System.out.println(ageFiled.get(stu2));
    }
}
